<script lang="ts" setup>
import { reactive, ref, watch, toRefs } from "vue"
import {
  createComboDataApi,
  updateComboDataApi,
  getComboDataApi1,
  getUserIdListSub,
  createZyID,
  copyCombo
} from "@/api/combo"
import {
  getComboDataApi2,
  getComboDataDetailApi,
  getComboDataDetailApi1,
  addRules,
  delRules,
  editRules,
  getRules,
  getRuleLogs,
  addRuleLogs,
  getRuleLogRw,
  getNoYj,
  delRuleLogs
} from "@/api/combo/index1"
import { type IGetComboData } from "@/api/combo/types/combo"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight, Edit, Delete } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { useComboSourceStore } from "@/store/modules/comboSource"
import { useTeamStore } from "@/store/modules/team"
import { useDepartmentStore } from "@/store/modules/department"
// import { checkPhoneNumber, checkID } from "@/utils/validate"
import { Plus } from "@element-plus/icons-vue"
import { formatDateTime } from "@/utils"
// import { uploadComboImageList } from "@/api/combo"
import type { TabsPaneContext } from "element-plus"
import { useUserStore } from "@/store/modules/user"
import { useCascaderAreaData } from "@vant/area-data"
import Editor from "@/components/RichText/index.vue"
const areaoptions = useCascaderAreaData()
const imageUrl = ref("")
defineOptions({
  name: "ComboList"
})
const activeName = ref("shelf")
const fileList = ref<any>([]) /**图片列表 */
const comboSourceStore = useComboSourceStore()
const teamStore = useTeamStore()
const userStore = useUserStore()
const departmentStore = useDepartmentStore()
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

/** 套餐来源数据获取 */
const comboSource = ref<any>([])
/**团队数据获取 */
const teamList = ref<any>([])
/**部门数据获取 */
const departmentList = ref<any>([])
/**部门团队组合数据 */
const departTeam = ref<any>([])

const willFlag = ref<any>(0)
/**代理数据 */
const userIdList = ref<any>([])
const userListEffect = () => {
  getUserIdListSub({}).then((res: any) => {
    console.log(res)
    userIdList.value = res.data
  })
}
userListEffect()
/**END */
//** 二维数组转字符串 */
const arrToStr = (objarr: any) => {
  const arrLen = objarr.length
  let row = "["
  for (let i = 0; i < arrLen; i++) {
    row += "["
    for (let j = 0; j < objarr[i].length; j++) {
      row += `'${objarr[i][j]}'`
      if (j < objarr[i].length - 1) {
        row += ","
      }
    }
    row += "]"
    if (i < arrLen - 1) {
      row += ","
    }
  }
  row += "]"
  return row
}

/** 佣金规则设置相关*/
const radio1 = ref<any>(null)
const formYjRef = ref<any>(null)
const dlgYj = ref<boolean>(false)
const tittleYj = ref<String>("新增佣金规则")
const data = reactive<any>({ formDataYj: {} })
const checkedAct = ref<boolean>(false) // 已激活复选
const checked1st = ref<boolean>(false) // 已首充复选
const checkedTotal = ref<boolean>(false) // 累计充值复选
const restYj = () => {
  formDataYj.value = {}
  checkedAct.value = false
  checked1st.value = false
  checkedTotal.value = false
  actChange(false)
  firstChange(false)
  totalChange(false)
}
const addYjRule = () => {
  tittleYj.value = "新增佣金规则"
  dlgYj.value = true
  curRuleId.value = undefined
  formData.timingRule = ""
}
//已激活复选框change事件
const actChange = (val: any) => {
  if (!val) {
    formDataYj.value.actCommission = ""
  }
}
//已首充发复选框change事件
const firstChange = (val: any) => {
  if (!val) {
    formDataYj.value.firstTopUp1 = ""
    formDataYj.value.firstTopUp2 = ""
    formDataYj.value.firstCommission1 = ""
    formDataYj.value.firstCommission2 = ""
  }
}
//已累计充发复选框change事件
const totalChange = (val: any) => {
  if (!val) {
    formDataYj.value.totalTopUp1 = ""
    formDataYj.value.totalTopUp2 = ""
    formDataYj.value.totalCommission1 = ""
    formDataYj.value.totalCommission2 = ""
  }
}
//佣金规则增删改查
//查
const ruleList = ref<any>([])
const getRuleList = (packageId: any) => {
  getRules({ packageId, type: 0 }).then((res: any) => {
    // console.log(res)
    if (res.code === 200) {
      ruleList.value = res.data
    }
  })
}
//增改
const curRuleId = ref<any>(undefined)
const { formDataYj } = toRefs(data)
const editRuleBtn = (row: any) => {
  curRuleId.value = row.id
  tittleYj.value = "修改佣金规则"
  formDataYj.value = JSON.parse(JSON.stringify(row))
  checkedAct.value = !!(formDataYj.value.actCommission && formDataYj.value.actCommission != 0)
  checked1st.value = !!(
    (formDataYj.value.firstTopUp1 && formDataYj.value.firstTopUp1 != 0) ||
    (formDataYj.value.firstTopUp2 && formDataYj.value.firstTopUp2 != 0)
  )
  checkedTotal.value = !!(
    (formDataYj.value.totalTopUp1 && formDataYj.value.totalTopUp1 != 0) ||
    (formDataYj.value.totalTopUp2 && formDataYj.value.totalTopUp2 != 0)
  )
  if (curRuleId.value === currentObj.value.commissionRuleId) {
    formData.timingRule = currentObj.value.timingRule
  } else {
    formData.timingRule = ""
  }
  dlgYj.value = true
}
const addOrEditRules = () => {
  if (!formData.timingRule) {
    ElMessage.warning("生效时间必填！")
    return
  }
  if (curRuleId.value) {
    editRules({
      ...formDataYj.value,
      logCreateTime: formData.timingRule,
      packageId: currentUpdateId.value,
      type: 0
    }).then((res: any) => {
      // console.log(res)
      if (res.code === 200) {
        ElMessage.success("修改成功")
        dlgYj.value = false
        getRuleList(currentUpdateId.value)
        if (formData.operator && formDataYj.value.actCommission) {
          optIsChange(formData.operator, false)
        }
      }
    })
  } else {
    addRules({
      ...formDataYj.value,
      packageId: currentUpdateId.value,
      logCreateTime: formData.timingRule,
      type: 0
    }).then((res: any) => {
      // console.log(res)
      if (res.code === 200) {
        ElMessage.success("添加成功")
        dlgYj.value = false
        getRuleList(currentUpdateId.value)
        if (formData.operator && formDataYj.value.actCommission) {
          optIsChange(formData.operator, true)
        }
      }
    })
  }
}
//规则删除
const delRuleBtn = (row: any) => {
  ElMessageBox.confirm(`正在删除：${row.ruleName}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delRules(row.id).then(() => {
      ElMessage.success("删除成功")
      getRuleList(currentUpdateId.value)
    })
  })
}
//规则切换
const currentRuleObj = ref<any>(null)
const changeRule = (val: any) => {
  ruleList.value.filter((item: any) => {
    if (item.id === val) {
      currentRuleObj.value = item
    }
  })
  // commissionRuleId
  // formData.sum = ""
  formData.commissionRuleId = currentRuleObj.value.id
  if (val && currentRuleObj.value.actCommission && formData.operator) {
    optIsChange(formData.operator, true)
  } else {
    formData.task = ""
  }
  // console.log(val, formDataYj.value, formData.operator)
}
//佣金规则变更记录
const dialogLogs = ref<any>(false)
const ruleLogs = ref<any>([])
const currentPId = ref<any>(undefined)
const handleLog = (packageId: any) => {
  currentPId.value = packageId
  getRuleLogs({ packageId, type: 0 }).then((res: any) => {
    if (res.code === 200) {
      ruleLogs.value = res.data
      dialogLogs.value = true
    }
  })
}
//手动添加佣金变更记录
const addLogForCommission = ref<any>(false)
const formCommission = ref<any>(null)
const DATA = reactive<any>({
  formDataCommission: {},
  formDataZy: {},
  formDataCN: {
    commonName: "",
    domains: []
  },
  rulesLogs: {
    ruleInfo: [{ required: true, trigger: "blur", message: "请输入规则内容" }],
    createTime: [{ required: true, trigger: "blur", message: "请选择生效时间" }]
  },
  formRulesZy: {
    goodsId: [{ required: true, trigger: "blur", message: "请输入上级套餐编码" }],
    packageSource: [{ required: true, trigger: "blur", message: "请选择上级来源" }]
  },
  formRulesCN: {}
})
const { formDataCommission, rulesLogs, formDataZy, formRulesZy, formDataCN, formRulesCN } = toRefs(DATA)
const addLogs = () => {
  addLogForCommission.value = true
}
const addSureLogs = () => {
  formCommission.value?.validate((valid: boolean) => {
    if (valid) {
      addRuleLogs({
        ...formDataCommission.value,
        packageId: currentPId.value
      }).then((res: any) => {
        console.log(res)
        if (res.code === 200) {
          handleLog(currentPId.value)
          addLogForCommission.value = false
        }
      })
    }
  })
}
const restCommission = () => {
  formCommission.value.resetFields()
}
//删除佣金变更记录
const delLogs = (row: any) => {
  ElMessageBox.confirm(`正在删除：${row.ruleInfo}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delRuleLogs({ id: row.id }).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("删除成功")
        handleLog(currentPId.value)
      }
    })
  })
}

/** END*/
//任务量变更记录
const dialogLogRw = ref<any>(false)
const ruleLogRw = ref<any>([])
const handleLogRw = (packageId: any) => {
  getRuleLogRw({ packageId, type: 0 }).then((res: any) => {
    console.log(res)
    if (res.code === 200) {
      ruleLogRw.value = res.data
      dialogLogRw.value = true
    }
  })
}
/** END*/
//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive<any>({
  name: "",
  superName: "",
  source: "",
  sku: "",
  superId: "",
  message: "",
  note: "",
  image: "",
  img: "",
  card: false,
  minAge: 16,
  maxAge: 60,
  operator: 1,
  area: eval('[["台湾省"], ["香港特别行政区"], ["澳门特别行政区"],["新疆维吾尔自治区"],["西藏自治区"],["云南省"]]'),
  state: "true",
  team: [],
  blackTeam: [],
  sum: "",
  imageList: "",
  guide: "", //敏感词
  isOpen: false, //是否对分销商展示
  task: "", //任务量
  resourceId: "",
  provider: "", //供应商
  pageUrl: "",
  contractId: "",
  masterId: "", //主套餐ID
  masterName: "", //主套餐名字
  commissionRuleId: "", //佣金规则ID
  timingRule: "", //佣金定时时间
  package_number_type: 0,
  commissionType: "", //佣金模式
  superClosing: "", //上级佣金结算口径
  superClosingType: "", //上级结算类型
  userIds: [], //可销售代理id
  nameObj: "" //套餐名组成
})

const formRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入套餐名称" }],
  sku: [{ required: true, trigger: "blur", message: "请输入套餐编码" }],
  // provider: [{ required: true, trigger: "blur", message: "请输入供应商" }],
  superName: [{ required: true, trigger: "blur", message: "请输入上级套餐名称" }],
  superId: [{ required: true, trigger: "blur", message: "请输入上级套餐编码" }],
  operator: [{ required: true, trigger: "blur", message: "请选择运营商" }],
  numberAddress: [{ required: true, trigger: "blur", message: "请输入归属地" }],
  source: [{ required: true, trigger: "blur", message: "请输选择套餐来源" }]
})

const handleAdd = () => {
  // resetForm()
  dialogVisible.value = true
}
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      uploadFuc()
    }
  })
}
const formRefCN = ref<any>(null)
const resetForm = () => {
  currentUpdateId.value = undefined
  ruleList.value = []
  clearValidate()
  formData.name = ""
  formData.numberAddress = ""
  formData.packingRemark = ""
  formData.isAutoSubmit = ""
  formData.inScale = ""
  formData.outScale = ""
  formData.package_number_type = 0
  formData.commissionType = ""
  formData.superClosing = ""
  formData.superClosingType = ""
  formData.source = ""
  formData.sku = ""
  formData.message = "<p><br/></p>"
  formData.note = ""
  formData.image = ""
  formData.team = []
  formData.blackTeam = []
  formData.sum = ""
  formData.imageList = ""
  formData.img = ""
  formData.superName = ""
  formData.superId = ""
  formData.contractId = ""
  formData.resourceId = ""
  formData.provider = ""
  formData.pageUrl = ""
  imageUrl.value = ""
  formData.card = false
  formData.area = eval(
    '[["台湾省"], ["香港特别行政区"], ["澳门特别行政区"],["新疆维吾尔自治区"],["西藏自治区"],["云南省"]]'
  )
  formData.maxAge = 60
  formData.minAge = 16
  formData.operator = 1
  fileList.value = []
  fileList1.value = []
  fileList2.value = []
  formData.state = "true"
  formData.guide = ""
  formData.task = ""
  formData.commissionRuleId = ""
  formData.timingRule = ""
  formData.sourceRemark = ""
  formData.masterId = ""
  formData.masterName = ""
  formData.changedCob = null
  formData.userIds = []
  formData.isOpen = false
  formData.nameObj = ""
  resetFormComboName(formRefCN.value)
}
//#endregion

//#region 删
// const handleDelete = (row: IGetComboData) => {
//   ElMessageBox.confirm(`正在删除套餐：${row.name}，确认删除？`, "提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning"
//   }).then(() => {
//     deleteComboDataApi(row.id).then(() => {
//       ElMessage.success("删除成功")
//       getTableData()
//     })
//   })
// }
//#endregion
/**上架/下架套餐 */
const upCombo = async (row: IGetComboData) => {
  ElMessageBox.confirm(`正在上架套餐：${row.name}，确认上架？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    handleUpdate(row, true, "true")
  })
}
const downCombo = async (row: IGetComboData) => {
  ElMessageBox.confirm(`正在下架套餐：${row.name}，确认下架？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    handleUpdate(row, true, "false")
  })
}
//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const currentObj = ref<any>(null)
const handleUpdate = (row: any, isUpOrDown: boolean, v: string) => {
  loading.value = true
  // console.log(row, 102)
  currentUpdateId.value = row.id
  getRuleList(row.id)
  getComboDataDetailApi1({ id: row.id })
    .then((res: any) => {
      if (res.code == 200) {
        currentObj.value = res.data
        formData.name = res.data.name
        formData.numberAddress = res.data.numberAddress
        formData.packingRemark = res.data.packingRemark
        formData.packingRemark = res.data.packingRemark
        formData.isAutoSubmit = res.data.isAutoSubmit
        formData.inScale = res.data.inScale
        formData.outScale = res.data.outScale
        formData.package_number_type = res.data.package_number_type
        formData.commissionType = res.data.commissionType
        formData.superClosing = res.data.superClosing
        formData.superClosingType = res.data.superClosingType
        formData.source = res.data.source
        formData.sku = res.data.sku
        formData.message = res.data.message
        // getMsg(row.message)
        formData.note = res.data.note
        formData.card = res.data.card
        formData.minAge = res.data.minAge
        formData.maxAge = res.data.maxAge
        formData.operator = res.data.operator
        formData.superName = res.data.superName
        formData.superId = res.data.superId
        formData.contractId = res.data.contractId
        formData.guide = res.data.guide
        formData.nameObj = res.data.nameObj
        formData.task = res.data.task
        formData.commissionRuleId = res.data.commissionRuleId
        radio1.value = res.data.commissionRuleId
        formData.pageUrl = res.data.pageUrl
        formData.resourceId = res.data.resourceId
        formData.provider = res.data.provider
        formData.isOpen = res.data.isOpen
        formData.sourceRemark = res.data.sourceRemark
        formData.masterId = res.data.masterId
        formData.masterName = res.data.masterName
        formData.expiryTime = res.data.expiryTime
        if (res.data.team) {
          formData.team = res.data.team.split(",")
        }
        if (res.data.blackTeam) {
          formData.blackTeam = res.data.blackTeam.split(",")
        }
        if (res.data.userIds) {
          formData.userIds = res.data.userIds.split(",")
        }
        formData.sum = res.data.sum
        if (v === "true") {
          formData.expiryTime = ""
        }
        //  formData.imageList = row.imageList
        /**字符串转二维数组 */
        formData.area = eval(res.data.area)
        formData.image = res.data.image?.split("/image/")[1]
        formData.img = res.data.img?.split("/image/")[1]
        if (res.data.image) {
          fileList.value = res.data.image?.split(",").map((item: any) => {
            return {
              url: item
            }
          })
        }

        if (res.data.img) {
          fileList2.value = res.data.img?.split(",").map((item: any) => {
            return {
              url: item
            }
          })
        }

        formData.imageList = res.data.imageList
          ?.split(",")
          .map((item: any) => {
            return item.split("/image/")[1]
          })
          .join()
        if (res.data.imageList) {
          fileList1.value = res.data.imageList
            .substring(0, res.data.imageList.length - 1)
            ?.split(",")
            .map((item: any) => {
              return {
                url: item
              }
            })
        }
        if (!isUpOrDown) {
          formData.state = res.data.state
          dialogVisible.value = true
        } else {
          formData.state = v
          updateComboDataApi({
            id: currentUpdateId.value,
            name: formData.name,
            numberAddress: formData.numberAddress,
            packingRemark: formData.packingRemark,
            isAutoSubmit: formData.isAutoSubmit,
            inScale: formData.inScale,
            outScale: formData.outScale,
            package_number_type: formData.package_number_type,
            commissionType: formData.commissionType,
            superClosing: formData.superClosing,
            superClosingType: formData.superClosingType,
            source: formData.source,
            sku: formData.sku,
            message: formData.message,
            note: formData.note,
            image: formData.image,
            card: formData.card,
            minAge: formData.minAge,
            maxAge: formData.maxAge,
            area: arrToStr(formData.area),
            state: formData.state,
            superName: formData.superName,
            resourceId: formData.resourceId,
            provider: formData.provider,
            pageUrl: formData.pageUrl,
            superId: formData.superId,
            contractId: formData.contractId,
            operator: formData.operator,
            team: formData.team.join(),
            blackTeam: formData.blackTeam.join(),
            sum: formData.sum,
            imageList: formData.imageList,
            img: formData.img,
            nameObj: formData.nameObj,
            userIds: formData.userIds.join(),
            task: formData.task,
            commissionRuleId: formData.commissionRuleId,
            timingRule: formData.timingRule,
            isOpen: formData.isOpen,
            sourceRemark: formData.sourceRemark,
            masterId: formData.masterId,
            masterName: formData.masterName,
            expiryTime: formData.expiryTime
          }).then(() => {
            if (v === "true") {
              ElMessage.success("上架成功")
            }
            if (v === "false") {
              ElMessage.success("下架成功")
            }
            dialogVisible.value = false
            getTableData()
          })
        }
      }
    })
    .finally(() => {
      loading.value = false
    })
  // selectedOptions.value = row.takeAddress.split("/")
}
//#endregion

//#region 查
const tableData = ref<IGetComboData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  name: "",
  sku: "",
  superSku: "",
  superName: "",
  state: "true",
  note: "",
  id: "",
  masterId: ""
  // team: userStore.teamName ? userStore.teamName : ""
})
const getTableData = () => {
  loading.value = true
  getComboDataApi1({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    state: searchData.state,
    name: searchData.name,
    sku: searchData.sku,
    superSku: searchData.superSku,
    superName: searchData.superName,
    note: searchData.note,
    masterId: searchData.masterId,
    willFlag: willFlag.value,
    id: searchData.id,
    team: "",
    blackTeam: ""
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.packageList
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
/**主套餐相关 */
const masterComobo = ref<any>([])
const getTableData1 = () => {
  loading.value = true
  getComboDataApi2({
    page: 1,
    size: 10000
  })
    .then((res) => {
      masterComobo.value = res.data.packageList
    })
    .catch(() => {
      masterComobo.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
getTableData1()
const changedCob = ref<any>(null)
const changeMasterCob = (val: any) => {
  // console.log(val)
  if (val) {
    // changedCob.value = masterComobo.value.filter((item: any) => {
    //   return item.id == val
    // })[0]
    loading.value = true
    getComboDataDetailApi({ id: val })
      .then((res: any) => {
        if (res.code == 200) {
          changedCob.value = res.data
          formData.numberAddress = changedCob.value.numberAddress
          formData.packingRemark = changedCob.value.packingRemark
          formData.inScale = changedCob.value.inScale
          formData.outScale = changedCob.value.outScale
          formData.package_number_type = changedCob.value.package_number_type
          formData.commissionType = changedCob.value.commissionType
          formData.source = changedCob.value.source
          formData.message = changedCob.value.message
          // getMsg(row.message)
          formData.note = changedCob.value.note
          formData.card = changedCob.value.card
          formData.minAge = changedCob.value.minAge
          formData.maxAge = changedCob.value.maxAge
          formData.operator = changedCob.value.operator
          formData.superName = changedCob.value.superName
          formData.superId = changedCob.value.superId
          formData.contractId = changedCob.value.contractId
          formData.guide = changedCob.value.guide
          formData.task = changedCob.value.task
          formData.commissionRuleId = changedCob.value.commissionRuleId
          formData.pageUrl = changedCob.value.pageUrl
          formData.resourceId = changedCob.value.resourceId
          formData.provider = changedCob.value.provider
          formData.isOpen = changedCob.value.isOpen
          formData.sourceRemark = changedCob.value.sourceRemark
          formData.expiryTime = changedCob.value.expiryTime
          formData.masterName = changedCob.value.name
          if (changedCob.value.blackTeam) {
            formData.blackTeam = changedCob.value.blackTeam.split(",")
          } else {
            formData.blackTeam = []
          }

          // if (row.team) {
          //   formData.team = row.team.split(",")
          // }
          if (changedCob.value.userIds) {
            formData.userIds = changedCob.value.userIds.split(",")
          }
          formData.sum = changedCob.value.sum
          //  formData.imageList = row.imageList
          /**字符串转二维数组 */
          formData.area = eval(changedCob.value.area)
          formData.imageList = changedCob.value.imageList
            ?.split(",")
            .map((item: any) => {
              return item.split("/image/")[1]
            })
            .join()
          if (changedCob.value.imageList) {
            fileList1.value = changedCob.value.imageList
              .substring(0, changedCob.value.imageList.length - 1)
              ?.split(",")
              .map((item: any) => {
                return {
                  url: item
                }
              })
          }
        } else {
          return false
        }
      })
      .finally(() => {
        loading.value = false
      })
  } else {
    resetForm()
  }
}
/**EＮＤ */
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}
//#endregion
/**不发货地区多选 */
const props = {
  multiple: true,
  checkStrictly: true,
  label: "text",
  value: "text"
}
/**可销售团队 */
/**不发货地区多选 */
const props1 = {
  multiple: true,
  emitPath: false,
  // checkStrictly: true,
  label: "name",
  value: "name"
}
/**套餐详情图上传 */
const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList.value = []
  } else {
    fileList.value = resfileList
  }
}

// 预览图片
const dialogImageUrl = ref("") /**预览url  */
const dialogVisible1 = ref(false) /**预览弹窗 */
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible1.value = true
}
// 移除图片
const handleRemove = (file: any) => {
  const list = fileList.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList.value = list
}
//确定上传
const uploadFuc = async () => {
  loading.value = true
  // if (fileList.value.length === 0) {
  //   ElMessage.error("请上传套餐详情图")
  //   return
  // }
  // const fileData = new FormData()
  // fileList.value.forEach((file: any) => {
  //   fileData.append("file", file.raw)
  // })
  // if (fileList.value[0].status === "ready") {
  //   await uploadComboImageList(fileData).then((res: any) => {
  //     if (res.code == 200) {
  //       formData.image = res.data.split("/image/")[1]
  //       fileList.value = []
  //     }
  //   })
  // }
  // if (formData.package_number_type == 2 && !formData.numberAddress) {
  //   ElMessage.error("选号类型为默认归属地时，选号归属地为必填项！")
  //   loading.value = false
  //   return false
  // }

  if (currentUpdateId.value === undefined) {
    await createComboDataApi({
      name: formData.name,
      numberAddress: formData.numberAddress,
      packingRemark: formData.packingRemark,
      isAutoSubmit: formData.isAutoSubmit,
      inScale: formData.inScale,
      outScale: formData.outScale,
      package_number_type: formData.package_number_type,
      commissionType: formData.commissionType,
      superClosing: formData.superClosing,
      superClosingType: formData.superClosingType,
      source: formData.source,
      sku: formData.sku,
      message: formData.message,
      note: formData.note,
      image: formData.image,
      card: formData.card,
      minAge: formData.minAge,
      maxAge: formData.maxAge,
      area: arrToStr(formData.area),
      state: formData.state,
      resourceId: formData.resourceId,
      provider: formData.provider,
      pageUrl: formData.pageUrl,
      superName: formData.superName,
      superId: formData.superId,
      contractId: formData.contractId,
      operator: formData.operator,
      team: formData.team.join(),
      blackTeam: formData.blackTeam.join(),
      sum: formData.sum,
      imageList: formData.imageList,
      img: formData.img,
      guide: formData.guide,
      nameObj: formData.nameObj,
      userIds: formData.userIds.join(),
      task: formData.task,
      commissionRuleId: formData.commissionRuleId,
      timingRule: formData.timingRule,
      isOpen: formData.isOpen,
      sourceRemark: formData.sourceRemark,
      masterId: formData.masterId,
      masterName: formData.masterName,
      expiryTime: formData.expiryTime
    })
      .then(() => {
        ElMessage.success("新增成功")
        dialogVisible.value = false
        getTableData()
        getNoYjList()
      })
      .finally(() => {
        loading.value = false
      })
  } else {
    await updateComboDataApi({
      id: currentUpdateId.value,
      name: formData.name,
      numberAddress: formData.numberAddress,
      packingRemark: formData.packingRemark,
      isAutoSubmit: formData.isAutoSubmit,
      inScale: formData.inScale,
      outScale: formData.outScale,
      package_number_type: formData.package_number_type,
      commissionType: formData.commissionType,
      superClosing: formData.superClosing,
      superClosingType: formData.superClosingType,
      source: formData.source,
      sku: formData.sku,
      message: formData.message,
      note: formData.note,
      image: formData.image,
      card: formData.card,
      minAge: formData.minAge,
      maxAge: formData.maxAge,
      area: arrToStr(formData.area),
      state: formData.state,
      pageUrl: formData.pageUrl,
      resourceId: formData.resourceId,
      provider: formData.provider,
      superName: formData.superName,
      superId: formData.superId,
      contractId: formData.contractId,
      operator: formData.operator,
      team: formData.team.join(),
      blackTeam: formData.blackTeam.join(),
      sum: formData.sum,
      imageList: formData.imageList,
      img: formData.img,
      guide: formData.guide,
      nameObj: formData.nameObj,
      userIds: formData.userIds.join(),
      task: formData.task,
      commissionRuleId: formData.commissionRuleId,
      timingRule: formData.timingRule,
      isOpen: formData.isOpen,
      sourceRemark: formData.sourceRemark,
      masterId: formData.masterId,
      masterName: formData.masterName,
      expiryTime: formData.expiryTime
    })
      .then(() => {
        ElMessage.success("修改成功")
        dialogVisible.value = false
        getTableData()
        getNoYjList()
      })
      .finally(() => {
        loading.value = false
      })
  }
}
//tabs切换

const handleClick = (tab: TabsPaneContext) => {
  paginationData.currentPage = 1
  // console.log(tab.paneName)
  if (tab.paneName === "willOff") {
    searchData.state = "true"
    willFlag.value = 1
  }
  if (tab.paneName == "shelf") {
    searchData.state = "true"
    willFlag.value = 0
  }
  if (tab.paneName == "offShelf") {
    searchData.state = "false"
    willFlag.value = 0
  }

  getTableData()
}
/**富文本 */
const getMsg = (val: any) => {
  if (val) {
    formData.message = val
  }

  // console.log(val)
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/**监听comboSource缓存 */
comboSourceStore.getCsourceFn()
watch(
  [() => comboSourceStore.comboSourceListStore],
  (newValue) => {
    comboSource.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**END */
/**监听 team 缓存 */

watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    teamList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**team END */
/**监听 department 缓存 */
const DTEFFECT = async () => {
  await teamStore.getTeamFn()
  await departmentStore.getDepartmentFn()
}
DTEFFECT()
watch(
  [() => departmentStore.departmentListStore],
  (newValue) => {
    departmentList.value = newValue.flat()
    /**实现部门团队数据合并 */
    departTeam.value = departmentList.value.map((item: any) => ({
      ...item,
      children: teamList.value.filter((childrenItem: any) => childrenItem.source === item.name)
    }))
    /**部门下无团队禁选 */
    departTeam.value.forEach((item: any) => {
      if (!item.children.length) {
        item.disabled = true
      }
      return item
    })
  },
  {
    immediate: true
  }
)

//上传套餐展示图
import { getToken } from "@/utils/cache/cookies"
import type { UploadProps } from "element-plus"

const fileList1 = ref<any>([]) /**图片列表 */
const dialogVisible4 = ref<boolean>(false)
const dialogImageUrl4 = ref<any>("")

const handleChageImg1 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList1.value = resfileList.filter((item: any) => item.uid !== file.uid) /**不符合规定的图片不在照片墙展示 */
  } else {
    // fileList1.value = resfileList
    // console.log(fileList1.value, 192)
    formData.imageList = resfileList
      .map((item: any) => {
        return item.response?.data.split("/image/")[1]
          ? item.response?.data.split("/image/")[1]
          : item.url.split("/image/")[1]
      })
      .join(",")
    console.log(formData.imageList, 10023)
  }
}

const handleRemove1: UploadProps["onRemove"] = (uploadFile: any, uploadFiles: any) => {
  console.log(uploadFiles, 180)
  // fileList1.value = uploadFiles
  formData.imageList = uploadFiles
    .map((item: any) => {
      return item.response?.data.split("/image/")[1]
        ? item.response?.data.split("/image/")[1]
        : item.url.split("/image/")[1]
    })
    .join(",")
  console.log(formData.imageList, 10024)
}

const handlePictureCardPreview1: UploadProps["onPreview"] = (uploadFile: any) => {
  dialogImageUrl4.value = uploadFile.url!
  dialogVisible4.value = true
}

//上传h5图
const fileList2 = ref<any>([]) /**图片列表 */
const dialogVisible5 = ref<boolean>(false)
const dialogImageUrl5 = ref<any>("")
const handleChageImg2 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList2.value = resfileList.filter((item: any) => item.uid !== file.uid) /**不符合规定的图片不在照片墙展示 */
  } else {
    formData.img = resfileList
      .map((item: any) => {
        return item.response?.data.split("/image/")[1]
          ? item.response?.data.split("/image/")[1]
          : item.url.split("/image/")[1]
      })
      .join()
  }
}

const handleRemove2: UploadProps["onRemove"] = (uploadFile: any, uploadFiles: any) => {
  // fileList1.value = uploadFiles
  formData.img = uploadFiles
    .map((item: any) => {
      return item.response?.data.split("/image/")[1]
        ? item.response?.data.split("/image/")[1]
        : item.url.split("/image/")[1]
    })
    .join()
}

const handlePictureCardPreview2: UploadProps["onPreview"] = (uploadFile: any) => {
  dialogImageUrl5.value = uploadFile.url!
  dialogVisible5.value = true
}

const headersOpts = {
  token: getToken()
}

/**department END */
// console.log(departTeam.value)

// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}

/** 生成资源ID */
const dialogZyId = ref<any>(false)
const formRefZy = ref<any>(null)
const creatId = () => {
  dialogZyId.value = true
}

/**文件改变 */
const fileListZy = ref<any>([]) /**图片列表 */
const dialogImageUrlZy = ref("") /**预览url  */
const dialogVisibleZy = ref(false) /**预览弹窗 */
const fileChange = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileListZy.value = resfileList.filter((item: any) => item.uid !== file.uid) /**不符合规定的图片不在照片墙展示 */
  } else {
    fileListZy.value = resfileList
    // console.log(fileListZy.value, "--------------------------11")
  }
}
// 移除图片
const handleRemoveZy = (file: any) => {
  const list = fileListZy.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileListZy.value = list
}
// 预览图片
const handlePictureCardPreviewZy = (file: any) => {
  dialogImageUrlZy.value = file.url
  dialogVisibleZy.value = true
}

/**确定上传 */
const createdId = async () => {
  formRefZy.value?.validate((valid: boolean) => {
    if (!valid) {
      return false
    }
  })
  if (fileListZy.value.length === 0) {
    ElMessage.warning("请上传产品图")
    return
  }
  const formDataZY = new FormData()
  fileListZy.value.forEach((file: any) => {
    formDataZY.append("packageSource", formDataZy.value.packageSource)
    formDataZY.append("goodsId", formDataZy.value.goodsId)
    formDataZY.append("channel", formDataZy.value.channel)
    formDataZY.append("file", file.raw)
  })
  await createZyID(formDataZY).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success("生成成功")
      formData.resourceId = res.data
      fileListZy.value = []
      dialogZyId.value = false
    }
  })
}
const resetFormZYID = () => {
  formRefZy.value.resetFields()
}

/**生成套餐名称 */
// const options = ref(["公司", "小额打款", "店铺链接"])
const options = ref([
  {
    key: "公司",
    value: "gs"
  },
  {
    key: "小额打款",
    value: "xk"
  },
  {
    key: "店铺链接",
    value: "dp"
  }
])
const dialogCN = ref<any>(false)
const viewName = ref<any>("")
const setCombo = () => {
  if (formData.masterName) {
    formDataCN.value.commonName = formData.masterName
  } else {
    formDataCN.value.commonName = formData.name.split("(")[0]
  }

  dialogCN.value = true
  if (formData.nameObj) {
    formDataCN.value.domains = JSON.parse(formData.nameObj)
  }
  if (formData.nameObj || formData.masterName) {
    viewName.value = formData.name
  }

  // setName(false)
}
const addDomain = () => {
  formDataCN.value.domains.push({
    key: Date.now(),
    type: "",
    month: "",
    price: "",
    total: ""
  })
}

const removeDomain = (item: any) => {
  const index = formDataCN.value.domains.indexOf(item)
  if (index !== -1) {
    formDataCN.value.domains.splice(index, 1)
    setName(false)
  }
}

const resetFormComboName = (formEl: any) => {
  if (!formEl) return
  formEl.resetFields()
  viewName.value = ""
  if (formData.nameObj) {
    formDataCN.value.domains = JSON.parse(formData.nameObj)
  } else {
    formDataCN.value.domains = []
  }
  if (formData.masterName) {
    formDataCN.value.commonName = formData.masterName
  } else {
    formDataCN.value.commonName = ""
  }
}
const setName = (flag: boolean) => {
  // console.log(formDataCN.value.domains)
  if (formDataCN.value.domains.length) {
    formData.nameObj = JSON.stringify(formDataCN.value.domains, null, 2)
  }
  const groupedByType = formDataCN.value.domains.reduce((accumulator: any, currentValue: any) => {
    // 检查accumulator中是否已经有当前type的数组
    if (!accumulator[currentValue.type]) {
      // 如果没有，则创建一个新数组并添加到accumulator中
      accumulator[currentValue.type] = []
    }
    // 将当前对象添加到对应type的数组中
    accumulator[currentValue.type].push(currentValue)
    // 返回accumulator以便进行下一次迭代
    return accumulator
  }, {})
  if (!groupedByType.gs && !groupedByType.xk && !groupedByType.dp && flag) {
    formData.name = formDataCN.value.commonName.replace(/\(/g, "（").replace(/\)/g, "）")
  }
  if (!groupedByType.gs && !groupedByType.xk && !groupedByType.dp) {
    viewName.value = formDataCN.value.commonName.replace(/\(/g, "（").replace(/\)/g, "）")
  }
  /**第一种情况 名称规则只存在公司补贴 */
  if (groupedByType.gs && !groupedByType.xk && !groupedByType.dp) {
    groupedByType.gs = groupedByType.gs.map((item: any) => {
      return `第${item.month}月补贴${item.price}元共补贴${item.total}个月`
    })
    if (flag) {
      formData.name = `${formDataCN.value.commonName
        .replace(/\(/g, "（")
        .replace(/\)/g, "）")}(公司${groupedByType.gs.join()})`
    }
    viewName.value = `${formDataCN.value.commonName
      .replace(/\(/g, "（")
      .replace(/\)/g, "）")}(公司${groupedByType.gs.join()})`
  }
  /**第二种情况 名称规则只存在小额打款 */
  if (groupedByType.xk && !groupedByType.gs && !groupedByType.dp) {
    groupedByType.xk = groupedByType.xk.map((item: any) => {
      return `第${item.month}月报销${item.price}元共报销${item.total}个月`
    })
    if (flag) {
      formData.name = `${formDataCN.value.commonName
        .replace(/\(/g, "（")
        .replace(/\)/g, "）")}(小额打款${groupedByType.xk.join()})`
    }
    viewName.value = `${formDataCN.value.commonName
      .replace(/\(/g, "（")
      .replace(/\)/g, "）")}(小额打款${groupedByType.xk.join()})`
  }
  /**第三种情况 名称规则只存在店铺链接 */
  if (!groupedByType.xk && !groupedByType.gs && groupedByType.dp) {
    groupedByType.dp = groupedByType.dp.map((item: any) => {
      return `第${item.month}月返${item.price}元共返${item.total}个月`
    })
    if (flag) {
      formData.name = `${formDataCN.value.commonName
        .replace(/\(/g, "（")
        .replace(/\)/g, "）")}(店铺链接${groupedByType.dp.join()})`
    }
    viewName.value = `${formDataCN.value.commonName
      .replace(/\(/g, "（")
      .replace(/\)/g, "）")}(店铺链接${groupedByType.dp.join()})`
  }
  /**第四种情况 名称规则存在公司，小额打款 */
  if (groupedByType.gs && groupedByType.xk && !groupedByType.dp) {
    groupedByType.gs = groupedByType.gs.map((item: any) => {
      return `第${item.month}月补贴${item.price}元共补贴${item.total}个月`
    })
    groupedByType.xk = groupedByType.xk.map((item: any) => {
      return `第${item.month}月报销${item.price}元共报销${item.total}个月`
    })
    if (flag) {
      formData.name = `${formDataCN.value.commonName
        .replace(/\(/g, "（")
        .replace(/\)/g, "）")}(公司${groupedByType.gs.join()};小额打款${groupedByType.xk.join()})`
    }
    viewName.value = `${formDataCN.value.commonName
      .replace(/\(/g, "（")
      .replace(/\)/g, "）")}(公司${groupedByType.gs.join()};小额打款${groupedByType.xk.join()})`
  }
  /**第五种情况 名称规则存在公司，店铺链接 */
  if (groupedByType.gs && !groupedByType.xk && groupedByType.dp) {
    groupedByType.gs = groupedByType.gs.map((item: any) => {
      return `第${item.month}月补贴${item.price}元共补贴${item.total}个月`
    })
    groupedByType.dp = groupedByType.dp.map((item: any) => {
      return `第${item.month}月返${item.price}元共返${item.total}个月`
    })
    if (flag) {
      formData.name = `${formDataCN.value.commonName
        .replace(/\(/g, "（")
        .replace(/\)/g, "）")}(公司${groupedByType.gs.join()};店铺链接${groupedByType.dp.join()})`
    }
    viewName.value = `${formDataCN.value.commonName
      .replace(/\(/g, "（")
      .replace(/\)/g, "）")}(公司${groupedByType.gs.join()};店铺链接${groupedByType.dp.join()})`
  }
  /**第六种情况 名称规则存在小额打款，店铺链接 */
  if (!groupedByType.gs && groupedByType.xk && groupedByType.dp) {
    groupedByType.xk = groupedByType.xk.map((item: any) => {
      return `第${item.month}月报销${item.price}元共报销${item.total}个月`
    })
    groupedByType.dp = groupedByType.dp.map((item: any) => {
      return `第${item.month}月返${item.price}元共返${item.total}个月`
    })
    if (flag) {
      formData.name = `${formDataCN.value.commonName
        .replace(/\(/g, "（")
        .replace(/\)/g, "）")}(店铺链接${groupedByType.dp.join()};小额打款${groupedByType.xk.join()})`
    }
    viewName.value = `${formDataCN.value.commonName
      .replace(/\(/g, "（")
      .replace(/\)/g, "）")}(店铺链接${groupedByType.dp.join()};小额打款${groupedByType.xk.join()})`
  }
  /**第七种情况 名称规则存在公司，小额打款，店铺链接 */
  if (groupedByType.gs && groupedByType.xk && groupedByType.dp) {
    groupedByType.gs = groupedByType.gs.map((item: any) => {
      return `第${item.month}月补贴${item.price}元共补贴${item.total}个月`
    })
    groupedByType.xk = groupedByType.xk.map((item: any) => {
      return `第${item.month}月报销${item.price}元共报销${item.total}个月`
    })
    groupedByType.dp = groupedByType.dp.map((item: any) => {
      return `第${item.month}月返${item.price}元共返${item.total}个月`
    })
    if (flag) {
      formData.name = `${formDataCN.value.commonName
        .replace(/\(/g, "（")
        .replace(
          /\)/g,
          "）"
        )}(公司${groupedByType.gs.join()};店铺链接${groupedByType.dp.join()};小额打款${groupedByType.xk.join()})`
    }
    viewName.value = `${formDataCN.value.commonName
      .replace(/\(/g, "（")
      .replace(
        /\)/g,
        "）"
      )}(公司${groupedByType.gs.join()};店铺链接${groupedByType.dp.join()};小额打款${groupedByType.xk.join()})`
  }

  if (flag) {
    dialogCN.value = false
  }
}
/**=============================== */
/**复制套餐名 */
import useClipboard from "vue-clipboard3"
const { toClipboard } = useClipboard()
const copy = async (text: any) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制！")
  } catch (e) {
    console.error(e)
  }
}

/**一键复制套餐 */
const handleCopy = async (row: any) => {
  ElMessageBox.confirm(`正在复制套餐：${row.name}，将生成一个全新套餐，确认复制？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    copyCombo(row.id).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success("操作成功")
        getTableData()
      }
    })
  })
}

const changeSuper = (val: any) => {
  console.log(val)
  if (val && val !== "欣网") {
    formData.provider = ""
  }
}
/**运营商变更时自动计算任务量规则 */
const selectOpt = () => {
  // if (currentRuleObj.value && currentRuleObj.value.actCommission) {
  changeRule(formData.commissionRuleId)
  // } else {
  //   formData.task = ""
  // }
}
const optIsChange = (val: any, e: boolean) => {
  if (val == 1) {
    formData.task = e
      ? (currentRuleObj.value.actCommission / 160).toFixed(1)
      : (formDataYj.value.actCommission / 160).toFixed(1)
  }
  if (val == 2) {
    formData.task = e
      ? (currentRuleObj.value.actCommission / 170).toFixed(1)
      : (formDataYj.value.actCommission / 170).toFixed(1)
  }
  if (val == 3) {
    formData.task = e
      ? (currentRuleObj.value.actCommission / 150).toFixed(1)
      : (formDataYj.value.actCommission / 150).toFixed(1)
  }
  if (val == 4) {
    formData.task = e
      ? (currentRuleObj.value.actCommission / 150).toFixed(1)
      : (formDataYj.value.actCommission / 150).toFixed(1)
  }
}
const defaultTime = new Date(2000, 1, 1, 0, 0, 0)
/**佣金数据未配置查询 */
const noYj = ref<any>([])
const dialogNoYj = ref<any>(false)
const getNoYjList = async () => {
  await getNoYj({}).then((res: any) => {
    if (res.code == 200) {
      noYj.value = res.data.map((item: any) => {
        return {
          id: item,
          text: `套餐ID:${item}未维护佣金政策，请及时配置！`
        }
      })
    }
  })
}
getNoYjList()
const handleSearchAllNoYj = () => {
  dialogNoYj.value = true
  getNoYjList()
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="id" label="Id查询">
          <el-input v-model.trim="searchData.id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="name" label="套餐名">
          <el-input v-model.trim="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="superSku" label="上级套餐编码" v-if="!userStore.teamName">
          <el-input v-model.trim="searchData.superSku" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="superName" label="上级套餐名" v-if="!userStore.teamName">
          <el-input v-model.trim="searchData.superName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="sku" label="套餐编码" v-if="!userStore.teamName">
          <el-input v-model.trim="searchData.sku" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="masterId" label="关联主套餐">
          <el-select v-model="searchData.masterId" filterable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in masterComobo" :key="item.id" :label="item.name" :value="item.id + ''" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="note" label="套餐别名" v-if="!userStore.teamName">
          <el-input v-model="searchData.note" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item
          ><van-swipe :autoplay="5000" style="height: 50px; margin-left: 50px; margin-top: 10px" vertical>
            <van-swipe-item v-for="item in noYj" :key="item.id">{{ item.text }}</van-swipe-item>
          </van-swipe>
          <el-button text type="primary" :icon="Search" @click="handleSearchAllNoYj"
            >查看所有未维护佣金套餐</el-button
          ></el-form-item
        >
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleAdd">添加套餐</el-button>
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="已上架套餐" name="shelf" />
          <el-tab-pane label="即将下架" name="willOff" />
          <el-tab-pane label="已下架套餐" name="offShelf" />
        </el-tabs>

        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="image" label="套餐主图" align="center">
            <template #default="scope">
              <img :src="scope.row.imageList.split(',')[0]" alt="" width="80" height="80" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="套餐名" align="center">
            <template #default="scope">
              <p style="cursor: pointer" @click="copy(scope.row.name)" title="点我复制套餐名">
                {{ scope.row.name }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="masterName" label="关联主套餐" align="center" />
          <!-- <el-table-column prop="sku" label="套餐sku" align="center" /> -->
          <el-table-column prop="source" label="套餐来源" align="center" />
          <el-table-column prop="superName" label="上级套餐名" align="center" />
          <el-table-column prop="superId" label="上级套餐编码" align="center" />
          <el-table-column prop="operator" label="运营商" align="center">
            <template #default="scope">
              <span v-if="scope.row.operator == 1">移动</span>
              <span v-else-if="scope.row.operator == 2">联通</span>
              <span v-else-if="scope.row.operator == 3">电信</span>
              <span v-else-if="scope.row.operator == 4">广电</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="isOpen" label="是否对分销商展示" align="center">
            <template #default="scope">
              <span v-if="scope.row.isOpen">是</span>
              <span v-if="!scope.row.isOpen">否</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="message" label="套餐详情" align="center">
            <template #default="scope">
              <el-tooltip v-if="scope.row.message" :content="scope.row.message" raw-content>
                <el-button>hover me</el-button>
                <span v-html="scope.row.message" class="text-ellipsis" />
              </el-tooltip>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="note" label="套餐别名" align="center" show-overflow-tooltip /> -->
          <el-table-column v-if="activeName === 'willOff'" prop="expiryTime" label="即将下架时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.expiryTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="date" label="发布时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="update" label="更新时间" align="center">
            <template #default="scope">
              <span v-if="scope.row.update">{{ formatDateTime(scope.row.update) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="280" align="left">
            <template #default="scope">
              <el-button type="primary" text bg size="small">
                <span v-if="scope.row.state === 'true'" @click="downCombo(scope.row)">下架</span>
                <span v-if="scope.row.state === 'false'" @click="upCombo(scope.row)">上架</span>
              </el-button>
              <br />
              <el-button
                style="margin: 5px 0"
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row, false, '')"
                >修改</el-button
              >
              <br />
              <el-button style="margin: 5px 0" type="primary" text bg size="small" @click="handleCopy(scope.row)"
                >一键复制</el-button
              >
              <br />
              <el-button
                v-if="
                  userStore.roles.join() !== '文员' &&
                  userStore.roles.join() !== '售后客服' &&
                  userStore.roles.join() !== '拼多多文员' &&
                  userStore.roles.join() !== '天猫平台文员' &&
                  userStore.roles.join() !== '京东平台文员' &&
                  userStore.roles.join() !== '抖音小店文员' &&
                  userStore.roles.join() !== '外部分销'
                "
                type="primary"
                text
                bg
                size="small"
                @click="handleLog(scope.row.id)"
                >佣金变更记录</el-button
              >
              <br />
              <el-button
                v-if="
                  userStore.roles.join() !== '文员' &&
                  userStore.roles.join() !== '售后客服' &&
                  userStore.roles.join() !== '拼多多文员' &&
                  userStore.roles.join() !== '天猫平台文员' &&
                  userStore.roles.join() !== '京东平台文员' &&
                  userStore.roles.join() !== '抖音小店文员' &&
                  userStore.roles.join() !== '外部分销'
                "
                type="primary"
                text
                bg
                size="small"
                @click="handleLogRw(scope.row.id)"
                >任务量变更记录</el-button
              >
              <!-- <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增套餐' : '修改套餐'"
      @close="resetForm"
      width="80%"
    >
      <el-form
        v-loading="loading"
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item prop="masterId" label="关联主套餐">
          <el-select
            v-model="formData.masterId"
            placeholder="请选择"
            style="width: 100%"
            filterable
            @change="changeMasterCob"
          >
            <el-option v-for="item in masterComobo" :key="item.id" :label="item.name" :value="item.id + ''" />
          </el-select>
        </el-form-item>
        <el-form-item prop="superName" label="上级套餐名">
          <el-input v-model="formData.superName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="superId" label="上级套餐编码">
          <el-input v-model="formData.superId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="source" label="套餐来源">
          <el-select
            v-model="formData.source"
            clearable
            :filterable="true"
            placeholder="请选择"
            style="width: 240px"
            @change="changeSuper"
          >
            <el-option v-for="item in comboSource" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sourceRemark" label="来源备注">
          <el-input v-model="formData.sourceRemark" placeholder="例如：敢探号-张三" />
        </el-form-item>
        <el-form-item prop="resourceId" label="资源ID">
          <el-input v-model="formData.resourceId" style="width: 70%" />
          <el-button type="primary" bg size="small" @click="creatId" style="margin-left: 10px"> 生成资源ID </el-button>
        </el-form-item>
        <el-form-item prop="provider" label="供应商" v-if="formData.source.includes('欣网')">
          <el-input v-model="formData.provider" />
        </el-form-item>
        <el-form-item prop="pageUrl" label="下单链接">
          <el-input v-model="formData.pageUrl" />
        </el-form-item>
        <el-form-item prop="contractId" label="合约ID">
          <el-input v-model="formData.contractId" />
        </el-form-item>
        <el-form-item prop="package_number_type" label="选号类型">
          <el-select v-model="formData.package_number_type" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="0" label="无" :value="0" />
            <el-option :key="1" label="号码归属地前置" :value="1" />
            <el-option :key="2" label="默认号码归属地" :value="2" />
            <el-option :key="3" label="无需号码归属地" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item prop="numberAddress" label="选号归属地" v-if="formData.package_number_type == 2">
          <el-input
            placeholder="需要选号的产品请填写号码池归属地，格式示例：河南省 焦作市 山阳区"
            v-model="formData.numberAddress"
          />
        </el-form-item>
        <el-form-item prop="name" label="套餐名">
          <el-input v-model="formData.name" placeholder="请输入" style="width: 80%" disabled />
          <el-button type="primary" bg size="small" @click="setCombo" style="margin-left: 10px"> 配置 </el-button>
        </el-form-item>
        <el-form-item prop="sku" label="套餐编码">
          <el-input v-model="formData.sku" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="operator" label="运营商">
          <el-select
            v-model="formData.operator"
            clearable
            placeholder="请选择"
            style="width: 240px"
            @change="selectOpt"
          >
            <el-option :key="1" label="移动" :value="1" />
            <el-option :key="2" label="联通" :value="2" />
            <el-option :key="3" label="电信" :value="3" />
            <el-option :key="4" label="广电" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item prop="packingRemark" label="包装备注">
          <el-input v-model="formData.packingRemark" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="outScale" label="省外占比">
          <el-input v-model="formData.outScale" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="inScale" label="省内占比">
          <el-input v-model="formData.inScale" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="message" label="套餐详情">
          <!-- <el-input v-model="formData.message" type="textarea" autosize placeholder="请输入" /> -->
          <Editor :value="formData.message" @updateValue="getMsg" />
        </el-form-item>
        <el-form-item prop="note" label="套餐别名">
          <el-input v-model="formData.note" type="textarea" autosize placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="card" label="上传身份证">
          <el-select v-model="formData.card" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="是" :value="true" />
            <el-option :key="2" label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item prop="age" label="年龄限制" class="ageInput">
          <el-input
            type="number"
            v-model="formData.minAge"
            placeholder="请输入最小年龄"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
          <span style="display: inline-block; padding: 0 5px">至</span>
          <el-input
            type="number"
            v-model="formData.maxAge"
            placeholder="请输入最大年龄"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
        </el-form-item>
        <el-form-item prop="guide" label="敏感词设置">
          <el-input type="textarea" placeholder="敏感词用英文逗号隔开,例如:小明,小红" v-model="formData.guide" />
        </el-form-item>
        <el-form-item prop="area" label="不发货地区">
          <el-cascader
            size="large"
            placeholder="可输入地址快速查询"
            :props="props"
            :options="areaoptions"
            v-model="formData.area"
            :filterable="true"
          />
        </el-form-item>
        <el-form-item prop="team" label="可销售团队">
          <!-- <el-select v-model="formData.team" clearable filterable placeholder="请选择" multiple style="width: 240px">
            <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select> -->
          <el-cascader
            size="large"
            placeholder="可输入快速查询"
            :props="props1"
            :options="departTeam"
            v-model="formData.team"
            :filterable="true"
            :show-all-levels="false"
          />
        </el-form-item>
        <el-form-item prop="blackTeam" label="黑户团队">
          <el-cascader
            disabled
            size="large"
            placeholder="可输入快速查询"
            :props="props1"
            :options="departTeam"
            v-model="formData.blackTeam"
            :filterable="true"
            :show-all-levels="false"
          />
        </el-form-item>
        <el-form-item prop="sum" label="佣金规则T1金额(配置)">
          <!--          <el-input v-model="formData.sum" placeholder="请输入" />-->
          <!--          佣金规则列表-->
          <el-radio-group v-model="radio1" size="large" style="width: 100%">
            <div class="bor3" v-for="item of ruleList" :key="item.id">
              <el-radio :label="item.id" @change="changeRule">
                <template v-if="ruleList.length">
                  <span>{{ item.ruleName }}：</span>
                  <span v-if="item.yjDesc">{{ item.yjDesc }}，</span>
                  <span v-if="item.dlJl">{{ item.dlJl }}，</span>
                  <span v-if="item.actCommission && item.actCommission != 0" class="blue"
                    >已激活,佣金{{ item.actCommission }}元。</span
                  >
                  <span v-if="item.firstTopUp1 && item.firstTopUp1 != 0 && item.firstCommission1 != 0" class="blue">
                    首充≥{{ item.firstTopUp1 }}元,佣金{{ item.firstCommission1 }}元。
                  </span>
                  <span v-if="item.firstTopUp2 && item.firstTopUp2 != 0 && item.firstCommission2 != 0" class="blue">
                    首充≥{{ item.firstTopUp2 }}元,佣金{{ item.firstCommission2 }}元。
                  </span>
                  <span v-if="item.totalTopUp1 && item.totalTopUp1 != 0 && item.totalCommission1 != 0" class="blue">
                    累计充值≥{{ item.totalTopUp1 }}元,佣金{{ item.totalCommission1 }}元。
                  </span>
                  <span v-if="item.totalTopUp2 && item.totalTopUp2 != 0 && item.totalCommission2 != 0" class="blue">
                    累计充值≥{{ item.totalTopUp2 }}元,佣金{{ item.totalCommission2 }}元。
                  </span>
                  <el-button
                    :disabled="item.id != radio1"
                    type="primary"
                    size="small"
                    :icon="Edit"
                    @click="editRuleBtn(item)"
                    >编辑</el-button
                  >
                  <el-button
                    :disabled="item.id != radio1"
                    type="danger"
                    size="small"
                    :icon="Delete"
                    @click="delRuleBtn(item)"
                  >
                    删除
                  </el-button>
                </template>
              </el-radio>
            </div>
          </el-radio-group>
          <el-button type="primary" @click="addYjRule" :disabled="!currentUpdateId">新增佣金规则</el-button>
        </el-form-item>
        <el-form-item prop="sum" label="佣金规则T1金额(应用)">
          <el-input v-model="formData.sum" type="textarea" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="commissionType" label="佣金模式">
          <el-select v-model="formData.commissionType" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="长分成" value="长分成" />
            <el-option :key="2" label="短分成" value="短分成" />
            <el-option :key="3" label="一次性分成" value="一次性分成" />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="task"
          label="任务量规则"
          v-if="userStore.roles.join() !== '文员' && userStore.roles.join() !== '售后客服'"
        >
          <el-input v-model="formData.task" placeholder="请输入" />
        </el-form-item>
        <el-form-item
          prop="superClosing"
          label="上级佣金结算口径"
          v-if="userStore.roles.join() !== '文员' && userStore.roles.join() !== '售后客服'"
        >
          <el-input v-model="formData.superClosing" placeholder="请输入" />
        </el-form-item>
        <el-form-item
          prop="superClosingType"
          label="上级佣金结算类型"
          v-if="userStore.roles.join() !== '文员' && userStore.roles.join() !== '售后客服'"
        >
          <el-input v-model="formData.superClosingType" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="isOpen" label="对分销商展示">
          <el-select v-model="formData.isOpen" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="是" :value="true" />
            <el-option :key="2" label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item prop="userIds" label="可销售分销商">
          <el-select
            :disabled="!formData.isOpen"
            v-model="formData.userIds"
            clearable
            filterable
            multiple
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in userIdList"
              :key="item.user_id"
              :label="item.user_name"
              :value="item.user_id + ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="currentUpdateId !== undefined" prop="searchDate" label="下架时间">
          <el-date-picker v-model="formData.expiryTime" type="datetime" :default-time="defaultTime" />
        </el-form-item>
        <el-form-item prop="isAutoSubmit" label="生产方式">
          <el-select v-model="formData.isAutoSubmit" clearable placeholder="是否自动提交上级" style="width: 240px">
            <el-option :key="1" label="自动生产" :value="0" />
            <el-option :key="2" label="手动生产" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item prop="imageList">
          <template #label>
            <span>套餐展示图</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content>
                套餐主图，建议尺寸：375px * 375px 用于展示产品缩略图，以及小程序产品详情页顶部的轮播图
              </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload
            v-model:file-list="fileList1"
            action="api/order/package/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview1"
            :on-remove="handleRemove1"
            :on-change="handleChageImg1"
            :headers="headersOpts"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible4">
            <img w-full :src="dialogImageUrl4" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item prop="image" style="display: none">
          <template #label>
            <span>套餐详情图</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content> 套餐详情图，建议尺寸 宽750px 高度随内容变化 用于小程序产品详情页的详情图 </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload
            :auto-upload="false"
            :file-list="fileList"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg"
            :disabled="fileList.length != 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="img" style="display: none">
          <template #label>
            <span>H5背景图</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content> H5背景图，建议尺寸 宽750px 高度随内容变化 用于H5下单落地页背景图 </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload
            v-model:file-list="fileList2"
            action="api/order/package/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview2"
            :on-remove="handleRemove2"
            :on-change="handleChageImg2"
            :headers="headersOpts"
            accept="image/*"
            :limit="1"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible5">
            <img w-full :src="dialogImageUrl5" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <!--    佣金规则弹窗-->
    <el-dialog v-model="dlgYj" :title="tittleYj" @close="restYj">
      <el-form ref="formYjRef" :model="formDataYj" label-width="100px" label-position="left">
        <el-form-item prop="ruleName" label="规则名称">
          <el-input v-model="formDataYj.ruleName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="yjDesc" label="佣金描述">
          <el-input v-model="formDataYj.yjDesc" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="dlJl" label="达量奖励">
          <el-input v-model="formDataYj.dlJl" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="defined" label="规则定义">
          <div class="newcon">
            <div class="newflex">
              <div class="newflexli1" style="padding: 15px 0">满足条件</div>
              <div class="newflexli2" style="padding: 15px 0">支出佣金</div>
            </div>
            <div class="newcon">
              <div class="newflex">
                <div class="newflexli1 newflex2">
                  <div class="newflexli11">
                    <el-checkbox v-model="checkedAct" label="已激活" size="large" @change="actChange" />
                  </div>
                  <div class="newflexli12" />
                </div>
                <div class="newflexli2">
                  <el-input
                    style="width: 60%; margin: 5px 0"
                    :disabled="!checkedAct"
                    type="text"
                    v-model="formDataYj.actCommission"
                    placeholder="请输入"
                  />
                </div>
              </div>
              <div class="newflex">
                <div class="newflexli1 newflex2">
                  <div class="newflexli11">
                    <el-checkbox v-model="checked1st" label="已首充" size="large" @change="firstChange" />
                  </div>
                  <div class="newflexli12">
                    <div>
                      <!--                      首充充值1-->
                      充值≥:
                      <el-input
                        style="width: 60%; margin: 5px 0"
                        :disabled="!checked1st"
                        type="text"
                        v-model="formDataYj.firstTopUp1"
                        placeholder="请输入"
                      />
                    </div>
                    <div>
                      <!--                      首充充值2-->
                      充值≥:
                      <el-input
                        style="width: 60%; margin: 5px 0"
                        :disabled="!checked1st"
                        type="text"
                        v-model="formDataYj.firstTopUp2"
                        placeholder="请输入"
                      />
                    </div>
                  </div>
                </div>
                <div class="newflexli2">
                  <!--                  首充佣金1-->
                  <el-input
                    style="width: 60%; margin: 5px 0"
                    :disabled="!checked1st"
                    type="text"
                    v-model="formDataYj.firstCommission1"
                    placeholder="请输入"
                  />
                  <!--                  首充佣金2-->
                  <el-input
                    style="width: 60%; margin: 5px 0"
                    :disabled="!checked1st"
                    type="text"
                    v-model="formDataYj.firstCommission2"
                    placeholder="请输入"
                  />
                </div>
              </div>
              <div class="newflex">
                <div class="newflexli1 newflex2">
                  <div class="newflexli11">
                    <el-checkbox v-model="checkedTotal" label="累计充值" size="large" @change="totalChange" />
                  </div>
                  <div class="newflexli12">
                    <div>
                      <!--                      累计充值1-->
                      充值≥:
                      <el-input
                        style="width: 60%; margin: 5px 0"
                        :disabled="!checkedTotal"
                        type="text"
                        v-model="formDataYj.totalTopUp1"
                        placeholder="请输入"
                      />
                    </div>
                    <div>
                      <!--                      累计充值2-->
                      充值≥:
                      <el-input
                        style="width: 60%; margin: 5px 0"
                        :disabled="!checkedTotal"
                        type="text"
                        v-model="formDataYj.totalTopUp2"
                        placeholder="请输入"
                      />
                    </div>
                  </div>
                </div>
                <div class="newflexli2">
                  <!--                  累计充值返佣1-->
                  <el-input
                    style="width: 60%; margin: 5px 0"
                    :disabled="!checkedTotal"
                    type="text"
                    v-model="formDataYj.totalCommission1"
                    placeholder="请输入"
                  />
                  <!--                  累计充值返佣2-->
                  <el-input
                    style="width: 60%; margin: 5px 0"
                    :disabled="!checkedTotal"
                    type="text"
                    v-model="formDataYj.totalCommission2"
                    placeholder="请输入"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="timingRule" label="生效时间">
          <el-date-picker v-model="formData.timingRule" type="datetime" :default-time="defaultTime" />
        </el-form-item>
        <el-form-item prop="ruleName" label="当前设定规则">
          <p style="margin: 0">
            <span>{{ formDataYj.yjDesc }}</span>
            <span>{{ formDataYj.dlJl }}</span>
            <span v-if="checkedAct">
              <span v-if="formDataYj.actCommission && formDataYj.actCommission != 0">
                已激活,佣金{{ formDataYj.actCommission }}元.
              </span>
            </span>
            <span v-if="checked1st">
              <span v-if="formDataYj.firstTopUp1 && formDataYj.firstTopUp1 != 0"
                >首充≥{{ formDataYj.firstTopUp1 }}元,佣金{{ formDataYj.firstCommission1 }}元</span
              >
              <span v-if="formDataYj.firstTopUp2 && formDataYj.firstTopUp2 != 0">
                首充≥{{ formDataYj.firstTopUp2 }}元,佣金{{ formDataYj.firstCommission2 }}元.</span
              >
            </span>
            <span v-if="checkedTotal">
              <span v-if="formDataYj.totalTopUp1 && formDataYj.totalTopUp1 != 0">
                累计充值≥{{ formDataYj.totalTopUp1 }}元,佣金{{ formDataYj.totalCommission1 }}元</span
              >
              <span v-if="formDataYj.totalTopUp2 && formDataYj.totalTopUp2 != 0">
                累计充值≥{{ formDataYj.totalTopUp2 }}元,佣金{{ formDataYj.totalCommission2 }}元.</span
              >
            </span>
          </p>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dlgYj = false">取消</el-button>
        <el-button type="primary" @click="addOrEditRules">确认</el-button>
      </template>
    </el-dialog>
    <!--    佣金规则变更记录-->
    <el-dialog v-model="dialogLogs">
      <template #title>
        <span>佣金规则变更记录</span>
        <el-button type="primary" size="small" style="margin-left: 20px" @click="addLogs">手动新增记录</el-button>
      </template>
      <el-table :data="ruleLogs">
        <el-table-column prop="createTime" label="生效时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="ruleInfo" label="规则" align="center" />
        <el-table-column prop="createBy" label="操作人" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="danger" size="small" @click="delLogs(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      任务量变更记录-->
    </el-dialog>
    <!--    任务量变更记录-->
    <el-dialog v-model="dialogLogRw" title="任务量变更记录">
      <el-table :data="ruleLogRw">
        <el-table-column prop="createTime" label="时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="taskInfo" label="规则" align="center" />
        <el-table-column prop="createBy" label="操作人" align="center" />
      </el-table>
    </el-dialog>
    <!-- 手动新增佣金变更记录 -->
    <el-dialog v-model="addLogForCommission" title="手动新增佣金变更记录" @close="restCommission">
      <el-form
        ref="formCommission"
        :rules="rulesLogs"
        :model="formDataCommission"
        label-width="100px"
        label-position="left"
      >
        <el-form-item prop="ruleInfo" label="规则内容">
          <el-input v-model="formDataCommission.ruleInfo" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="createTime" label="生效时间">
          <el-date-picker v-model="formDataCommission.createTime" type="datetime" :default-time="defaultTime" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addLogForCommission = false">取消</el-button>
        <el-button type="primary" @click="addSureLogs">确认</el-button>
      </template>
    </el-dialog>
    <!-- 生成资源ID -->
    <el-dialog v-model="dialogZyId" title="生成资源ID" @close="resetFormZYID" width="80%">
      <el-form ref="formRefZy" :model="formDataZy" :rules="formRulesZy" label-width="100px" label-position="left">
        <el-form-item prop="packageSource" label="上级来源">
          <el-select v-model="formDataZy.packageSource" placeholder="请选择" style="width: 240px" filterable>
            <el-option v-for="item in comboSource" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item prop="goodsId" label="上级套餐编码">
          <el-input v-model="formDataZy.goodsId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="channel" label="触点编码">
          <el-input v-model="formDataZy.channel" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="file" label="产品图">
          <el-upload
            :file-list="fileListZy"
            list-type="picture-card"
            multiple
            :on-change="fileChange"
            accept="image/*"
            :show-file-list="true"
            :auto-upload="false"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreviewZy(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-delete" @click="handleRemoveZy(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisibleZy">
            <img w-full :src="dialogImageUrlZy" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogZyId = false">取消</el-button>
        <el-button type="primary" @click="createdId">确认</el-button>
      </template>
    </el-dialog>
    <!-- 套餐名配置 -->
    <el-dialog v-model="dialogCN" title="套餐名配置" width="1200px">
      <el-form ref="formRefCN" :model="formDataCN" :rules="formRulesCN" label-width="100px" label-position="left">
        <el-form-item prop="commonName" label="通用名">
          <el-input v-model="formDataCN.commonName" placeholder="请输入" @input="setName(false)" />
        </el-form-item>
        <el-form-item
          v-for="(domain, index) in formDataCN.domains"
          :key="domain.key"
          :prop="'domains.' + index + '.type'"
          style="margin-left: 30px"
        >
          <el-select
            v-model="domain.type"
            placeholder="请选择类型"
            size="mini"
            style="width: 160px"
            @change="setName(false)"
          >
            <el-option v-for="item in options" :key="item.value" :label="item.key" :value="item.value" /> </el-select
          >第<el-input v-model="domain.month" placeholder="请输入月份" style="width: 160px" @input="setName(false)" />
          <span v-if="domain.type === 'gs'">月补贴</span>
          <span v-if="domain.type === 'xk'">月报销</span>
          <span v-if="domain.type === 'dp'">月返</span>
          <!-- <span v-if="domain.type === '店铺链接'">次月返</span> -->
          <el-input
            type="number"
            min="1"
            v-model="domain.price"
            placeholder="请输入金额"
            style="width: 160px"
            @input="setName(false)"
          />元
          <span v-if="domain.type === 'gs'">共补贴</span>
          <span v-if="domain.type === 'xk'">共报销</span>
          <span v-if="domain.type === 'dp'">共返</span>
          <!-- <span v-if="domain.type === '店铺链接'">次月返</span> -->
          <el-input
            type="number"
            min="1"
            v-model="domain.total"
            placeholder="请输入总共返几个月"
            style="width: 200px"
            @input="setName(false)"
          />个月
          <el-button @click.prevent="removeDomain(domain)"> 删除 </el-button>
        </el-form-item>
        <el-form-item style="margin-left: 30px">
          <el-button type="primary" @click="addDomain">新增拼接内容</el-button>
          <el-button @click="resetFormComboName(formRefCN)">重置</el-button>
        </el-form-item>
        <el-form-item label="最终名称预览">
          <el-input type="textarea" v-model="viewName" style="width: 100%" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogCN = false">取消</el-button>
        <el-button type="primary" @click="setName(true)">确认</el-button>
      </template>
    </el-dialog>
    <!-- 未维护佣金套餐 -->
    <el-dialog v-model="dialogNoYj" title="未维护佣金套餐" width="1200px">
      <el-scrollbar height="600px">
        <el-table :data="noYj">
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="text" label="说明" align="center" />
          <el-table-column fixed="right" label="操作" width="280" align="left">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row, false, '')"
                >去维护</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
  :deep(.el-form-item__label) {
    width: 100px !important;
  }
}

:deep(.el-form-item__label) {
  width: 130px !important;
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.ageInput :deep(.el-input) {
  width: 20% !important;
}
:deep(.el-loading-parent--relative) {
  z-index: 199999 !important;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
:deep(.el-cascader) {
  width: 567px !important;
}
:deep(.el-radio:last-child) {
  white-space: break-spaces;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.newcon {
  border: 1px #eaeaea solid;
  border-bottom: 0;
}
.newflex {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  text-align: center;
  border-bottom: 1px #eaeaea solid;
}
.newflex2 {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.newflexli1 {
  -webkit-box-flex: 2;
  -ms-flex: 2;
  flex: 2;
}
.newflexli2 {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border-left: 1px #eaeaea solid;
}
.newflexli11 {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  line-height: 36px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.newflexli12 {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  border-left: 1px #eaeaea solid;
}
.bor3 {
  width: 100%;
  border: 1px #eaeaea solid;
  background: #eaeaea;
  padding: 10px;
  border-radius: 3px;
  margin-bottom: 10px;
}
.van-swipe-item {
  color: red;
  font-size: 20px;
}
</style>
